#!/bin/bash -e

echo	"


=====================================================================

                 Utility to create Linux From Scratch
                   http://www.linuxfromscratch.org


                    Based on Version SVN-20121015

=====================================================================



"

# tigger a password input right from the beginning
sudo ls > /dev/null



# the location of the package
export CUSTLFS=/home/tnick/code/my-dev/LFS


# the user to use when doing this job
export LFS_USER=lfs

# the device that should be used as /root 
# leave empty if the target is a folder
#export LFS_DEV=/dev/sda6
export LFS_DEV=

# the device that should be used as swap space
# leave empty if the target is a folder or you don't want to use a swap partition
# export LFS_DEV_SWAP=/dev/sda7
export LFS_DEV_SWAP=

# the path to the target directory inside host system
# if $LFS_DEV is not empty it gets mounted in this location
# if $LFS_DEV is empty this directory should exist
#export LFS=/mnt/lfs1
export LFS=/home/tnick/code/my-dev/LFS/build

# the file that contains the list of files to be downloaded in $LFS/sources
export WGET_LIST=$CUSTLFS/wget-list
# the file that contains the checksums for $LFS/sources
export WGET_MD5=$CUSTLFS/md5sums
# the content of this directory is copied into $LFS/sources before download
export SOURCES_CACHE=$CUSTLFS/cache

export MAKEFLAGS="-j 2"

# where to load/save the tools directory (leave blank to skip this step)
export SAVE_TOOLS=$CUSTLFS

# uses the cached tools; leave empty to generate the tools
export CACHED_TOOLS="tools.tar.gz"

# use provided user without asking anything (true)
# or check the user (false)
CHECK_USER=false

# skip the verification step or not
VERIFY_VERSIONS=false

# skip file system step (directory/partition initialisation) 
# this means 
# - for partition that it is formated and mounted in $LFS
# - for directory that it exists
SETUP_FS=true

# ignore wget; if set to true WGET will compare the timestamps to see if
# it should download something; if set to false nothing is downloaded
ALLOW_WGET=false

# allow checking md5 sums of downloaded packages
ALLOW_MD5CHECK=false

# can be used to disable the copy of sources when we know they are in place
COPY_SOURCES_IN_PLACE=false

# can be used to disable the copy of tools when we know they are in place
COPY_TOOLS_IN_PLACE=true

# clean the environment before starting the actual script
CLEAN_TARGET_DIR=false






if $CLEAN_TARGET_DIR; then
	sudo umount $LFS/dev/pts > /dev/null
	sudo umount $LFS/dev/shm > /dev/null
	sudo umount $LFS/dev > /dev/null
	sudo umount $LFS/proc > /dev/null
	sudo umount $LFS/sys  > /dev/null
	sudo rm -rfv $LFS/dev > /dev/null
	sudo rm -rfv $LFS/proc > /dev/null
	sudo rm -rfv $LFS/sys  > /dev/null
	#sudo rm -rfv $LFS/tools > /dev/null
fi


if $VERIFY_VERSIONS; then
	# check requirements
	$CUSTLFS/version-check.sh > $CUSTLFS/tmp.txt
	more $CUSTLFS/tmp.txt
	rm $CUSTLFS/tmp.txt
	check_resp=
	echo	""
	echo	"Please examine the output above and type"
	echo	"Y if it is OK to proceed or"
	echo	"N to exit now"
	echo	""
	while [ -z "$check_resp" ];do

		read check_resp
		if [ ! -z "$check_resp" ]; then
			if [ "$check_resp" == "y" ]; then
				echo "" > /dev/null
			elif [ "$check_resp" == "Y" ]; then
				echo "" > /dev/null
			elif [ "$check_resp" == "n" ]; then
				echo	"Exit on user's request."
				exit -1
			elif [ "$check_resp" == "N" ]; then
				echo	"Exit on user's request."
				exit -1
			else
				echo	"... invalid input. Enter Y or N ...."
				check_resp=
			fi
		fi
	done							
fi




# deal with the swap space partition
if [ ! -z "$LFS_DEV_SWAP" ];then
	echo	""
	echo	"Swap partition <$LFS_DEV_SWAP> is being activated"
	echo	""	
	sudo mkswap $LFS_DEV_SWAP
	sudo /sbin/swapon -v $LFS_DEV_SWAP
fi


if $SETUP_FS; then
	# see if we're using a partition or an output directory
	if [ ! -z "$LFS_DEV" ];then
		echo	""
		echo	""
		echo	"---------------------------------------------"
		echo	""
		echo	"    Chapter 2. Preparing a New Partition     "
		echo	""
		echo	"---------------------------------------------"
		echo	""
		echo	""
		echo	"---------------------------------------------"
		echo	"2.3. Creating a File System on the Partition "
		echo	"---------------------------------------------"
	
		E2FSPROGS=e2fsprogs-1.42.5
	
		cd /tmp
		if [ ! -f "./$E2FSPROGS.tar.gz" ];then
			echo	"We're downloading e2fsprogs..."
			wget -nv --tries=6 --waitretry=10  \
				http://prdownloads.sourceforge.net/e2fsprogs/$E2FSPROGS.tar.gz \
				-O ./$E2FSPROGS.tar.gz			
		fi
		if [ ! -d "./$E2FSPROGS" ]; then
			echo	"Extracting e2fsprogs..."
			tar -xzvf ./$E2FSPROGS.tar.gz > /dev/null
			echo	"Configure & build e2fsprogs..."
			cd ./$E2FSPROGS
			mkdir -v build
			cd ./build
			../configure
			make #note that we intentionally don't 'make install' here!
		fi	

		echo	"Formatting target partition..."
		sudo /tmp/$E2FSPROGS/build/misc/mke2fs -jv $LFS_DEV
		# cd /tmp
		# rm -rfv ./$E2FSPROGS

		echo	""
		echo	"-------------------------------------------"
		echo	""
		echo	"Installing on physical partition <$LFS_DEV>"
		echo	"That will be mounted as <$LFS>"
		echo	""
	
		# check if the directory already exists
		if [ -d "$LFS" ];then
			echo	""
			echo	"Directory <$LFS> already exists."
			echo	"Specify another directory and press RETURN. Leave empty to exit."
			read LFS
			if [ -z "${LFS}" ];then
				echo	"Exit on user's request."
				exit -1
			fi
	
		fi
	
		# mount the partition
		sudo mkdir -pv $LFS
		sudo mount -v -t ext3 $LFS_DEV $LFS
	
	
	
	
	
	else
		echo	""
		echo	"-------------------------------------------"
		echo	""
		echo	"Installing on local directory $LFS"
		echo	""
		if [ ! -d "$LFS" ];then
			echo	""
			echo	"Directory <$LFS> does not exist."
			echo	"Specify another directory and press RETURN. Leave empty to exit."
			read LFS
			if [ -z "${LFS}" ];then
				echo	"Exit on user's request."
				exit -1
			fi
		fi
	
	fi
	echo	"-------------------------------------------"
	echo	""
fi


echo	""
echo	""
echo	"---------------------------------------------"
echo	""
echo	"       Chapter 3. Packages and Patches       "
echo	""
echo	"---------------------------------------------"
echo	""
echo	""
echo	"Create sources directory <$LFS/sources>; make it sticky."
if [ ! -d "$LFS/sources" ]; then
	sudo mkdir $LFS/sources
fi
sudo chmod -v a+wt $LFS/sources


# copy the cache in source
if [ ! -z "$SOURCES_CACHE" ];then

	if [ ! -d "$SOURCES_CACHE" ];then
		echo	""
		echo	"Cache directory for sources <$SOURCES_CACHE>"
		echo	"does not exists"
		echo	""
		exit -1
	fi
	
	echo	""
	echo	"Copying the cached packages from "
	echo	"<$SOURCES_CACHE> to <$LFS/sources>"
	echo	""
	cd $SOURCES_CACHE
	if $COPY_SOURCES_IN_PLACE; then
		for f_to_cp in *; do
			if [ "$f_to_cp" != "*" ]; then
				cp -r "$f_to_cp" "$LFS/sources/"
			fi
		done
	fi
	
	
fi

# download source packages
cd $LFS/sources
if $ALLOW_WGET; then
	echo	"Retrieving source packages using wget:"
	echo	"- non-verbose mode is on"
	echo	"- for each file there will be 6 attempts"
	echo	"- we will wait 10 seconds after each failed attempt"
	echo	"- if a package is already present, it will be"
	echo	"  redownloaded only if it's timestamp indicates "
	echo	"  that it's newer"
	echo	" - the list of files to use: $WGET_LIST"
	wget -nv --tries=6 --waitretry=10 -N -i $WGET_LIST -P $LFS/sources
fi

echo	""
echo	"Checking md5 sums..."
if $ALLOW_MD5CHECK; then
	md5sum -c $WGET_MD5
fi


echo	""
echo	""
echo	"---------------------------------------------"
echo	""
echo	"        Chapter 4. Final Preparations        "
echo	""
echo	"---------------------------------------------"
echo	""
echo	""
		
		
		
echo	"
All programs compiled in Chapter 5 will be 
installed under $LFS/tools to keep them
separate from the programs compiled in 
Chapter 6. The programs compiled here are 
temporary tools and will not be a part of the 
final LFS system. By keeping these programs in 
a separate directory, they can easily be discarded 
later after their use. This also prevents these 
programs from ending up in the host production 
directories (easy to do by accident in Chapter 5). 
"

if [ ! -d $LFS/tools ]; then
	sudo mkdir -v $LFS/tools
fi

echo	"create a /tools symlink on the host system."
if [ ! -h "/tools" ]; then
	sudo ln -sv "$LFS/tools" /
fi
		

# make sure lfs group exists
grp_check=$(grep -i "lfs" /etc/group)
if [ -z "$grp_check" ];then
	echo	"Creating usergroup   <lfs>"
	sudo groupadd lfs
fi


if $CHECK_USER ; then 
	if id -u "$LFS_USER" >/dev/null 2>&1; then
		# sudo userdel $LFS_USER
		echo	"User    <$LFS_USER>    already exists."
		echo	"Type in a new name and press RETURN. Leave empty to stop."
		read LFS_USER
		if [ -z "${LFS_USER}" ];then
			echo	"Exit on user's request."
			exit -1
		fi
	fi
	echo	"

	Using <$LFS_USER> as user. 
	- user login shell: /bin/bash
	- group: lfs
	- creating empty home directory: /home/$LFS_USER
	Password for new user account is now requested.

	"
	sudo useradd -s /bin/bash -g lfs -m -k /dev/null $LFS_USER
	sudo passwd $LFS_USER
fi

echo	"User $LFS_USER should own $LFS/sources"
sudo chown -v $LFS_USER $LFS/sources
sudo chown -v $LFS_USER $LFS/tools

# see if we can rely on cached tools
if [ ! -z "$CACHED_TOOLS" ]; then	
	if [ ! -f "$SAVE_TOOLS/$CACHED_TOOLS" ]; then
		echo	""
		echo	""
		echo	"Warning! There are no cached tools to use"
		echo	"$SAVE_TOOLS/$CACHED_TOOLS"
		echo	""
		echo	""
		CACHED_TOOLS=""
	fi
fi


if [ -z "$CACHED_TOOLS" ]; then	
	echo	"Login as $LFS_USER"
	sudo -u $LFS_USER -g lfs -E -H bash -c "$CUSTLFS/lfs-side.sh"
else
	echo	"Extracting cached tools from"
	echo	"$SAVE_TOOLS/$CACHED_TOOLS"
	sudo rm -rfv $LFS/tools/* > /dev/null
	cd $LFS
	if $COPY_TOOLS_IN_PLACE; then
		sudo tar -zxf $SAVE_TOOLS/$CACHED_TOOLS
	fi
fi

echo	"
Change the ownership of the $LFS/tools directory to user root
"
cd $LFS
sudo chown -R root:root $LFS/tools

# if we have generated a new set of tools
if [ -z "$CACHED_TOOLS" ]; then	
	if [ ! -z "$SAVE_TOOLS" ]; then
		echo	"/tools is now being archived for future use..."
		pushd $LFS > /dev/null
		if [ -f "$SAVE_TOOLS/tools.tar.gz" ]; then
			sudo rm $SAVE_TOOLS/tools.tar.gz
		fi
		sudo tar -pczf $SAVE_TOOLS/tools.tar.gz ./tools
		popd
	fi
fi








echo	""
echo	""
echo	"---------------------------------------------"
echo	""
echo	" Chapter 6. Installing Basic System Software "
echo	""
echo	"---------------------------------------------"
echo	""
echo	""

 # It is important that all the commands throughout the remainder of
 # this chapter and the following chapters are run from within the 
 # chroot environment. If you leave this environment for any reason 
 # (rebooting for example), ensure that the virtual kernel filesystems 
 # are mounted as explained in Section 6.2.2, “Mounting and Populating 
 # /dev” and Section 6.2.3, “Mounting Virtual Kernel File Systems” 
 # and enter chroot again before continuing with the installation. 


 
echo	"---------------------------------------------"
echo	" 6.2. Preparing Virtual Kernel File Systems "
echo	"---------------------------------------------"
echo	""
echo	"Creating directories onto which the file systems will be mounted "
sudo mkdir -v $LFS/{dev,proc,sys}


echo	"
The device nodes must be created on the hard disk so 
that they are available before udevd has been started,
and additionally when Linux is started with init=/bin/bash."
sudo mknod -m 600 $LFS/dev/console c 5 1
sudo mknod -m 666 $LFS/dev/null c 1 3

echo	"
Bind mounting the host system's /dev directory. 
This is a special type of mount that allows you 
to create a mirror of a directory or mount 
point to some other location."
sudo mount -v --bind /dev $LFS/dev

sudo mount -vt devpts devpts $LFS/dev/pts
sudo mount -vt proc proc $LFS/proc
sudo mount -vt sysfs sysfs $LFS/sys

echo	"
In some host systems, /dev/shm is a symbolic 
link to /run/shm. Inside a chroot environment, 
this symbolic link needs to be changed to a normal 
directory before mounting as a temporary file system."
if [ -h /dev/shm ]; then
   sudo rm -f $LFS/dev/shm
   sudo mkdir $LFS/dev/shm
fi
sudo mount -vt tmpfs shm $LFS/dev/shm



echo	""
echo	"---------------------------------------------"
echo	" 6.4. Entering the Chroot Environment"
echo	"---------------------------------------------"
echo	"
Enter the realm that is, at the moment, 
populated with only the temporary tools:
- clear all variables in chroot environment
- HOME, TERM, PS1, and PATH variables are set again
- we're using bash inside and hash is disabled.
"
sudo cp -f $CUSTLFS/libraries.sh $LFS/tools/bin/libraries.sh
sudo chown -R root:root $LFS/tools/bin/libraries.sh
sudo chroot "$LFS" /tools/bin/bash --login +h /tools/bin/libraries.sh "/root" "$TERM" '\u:\w\$ ' "/bin:/usr/bin:/sbin:/usr/sbin:/tools/bin"

#
    # /tools/bin/bash 
     
    
    
# From this point on, there is no need to 
# use the LFS variable anymore, because all 
# work will be restricted to the LFS file system. 







# after process is done this is how we enter chroot
#chroot "$LFS" /usr/bin/env -i \
    #HOME=/root TERM="$TERM" PS1='\u:\w\$ ' \
    #PATH=/bin:/usr/bin:/sbin:/usr/sbin \
    #/bin/bash --login







echo	""
echo	""
echo	"---------------------------------------------"
echo	""  
echo	"              Chapter X. Clean up            "
echo	""
echo	"---------------------------------------------"
echo	""
echo	""
		
		
echo	"Removing /tools symbolic link"
sudo rm "/tools"

sudo umount $LFS/dev/pts
sudo umount $LFS/dev/shm
sudo umount $LFS/dev
sudo umount $LFS/proc
sudo umount $LFS/sys 
sudo rm -rfv $LFS/dev
sudo rm -rfv $LFS/proc
sudo rm -rfv $LFS/sys 


if $SETUP_FS; then
	echo	"Unmounting partition and mount folder"
	if [ ! -z "$LFS_DEV" ]; then
		sudo umount $LFS_DEV
		sudo rm -rfv $LFS_DEV
	fi
fi


echo	"

                    Succesfull exit

=====================================================================

"
